<?php

/**
 * Adminhtml Image Grid/Edit Controller
 */
class AW_Imagetest_Admin_ImageController extends Mage_Adminhtml_Controller_Action
{
    /**
     * Init Grid Container
     * @return AW_Imagetest_Admin_ImageController
     */
    protected function _initAction()
    {
        if (Mage::helper('imagetest')->checkVersion('1.4.0.0')){
            $this->_title($this->__('Catalog'))
                ->_title($this->__('Image Testimonials'))
                ->_title($this->__('Image'));
        }

        $this->loadLayout()
            ->_setActiveMenu('catalog/imagetest')
            ->_addBreadcrumb(Mage::helper('imagetest')->__('All images'), Mage::helper('imagetest')->__('All images'));

        return $this;
    }

    /**
     * Show all images
     */
    public function indexAction()
    {
        $this->_initAction()
            ->_addContent($this->getLayout()->createBlock('imagetest/adminhtml_image'))
            ->renderLayout()
            ;
    }

    /**
     * Show pendign images
     */
    public function pendingAction()
    {
        $this->_initAction()
            ->_addContent(
                $this->getLayout()->createBlock('imagetest/adminhtml_image', '', array('pending'=>true)))
                ->renderLayout()
                ;
    }

    /**
     * Update status to $status
     * @param int|string $id
     * @param int $status
     */
    protected function _updateStatus($id, $status)
    {
        $image = Mage::getModel('imagetest/image')->load($id);
        if ($image->getId() && ($status !== null)){
            $image->setStatus($status);
            try{
                $image->save();
                return true;
            } catch(Exception $e) {
                return false;
            }
        }
        return false;
    }
   
    /**
     * Update state to $state
     * @param int|string $id
     * @param int $status
     */
    protected function _updateState($id, $state)
    {
        $image = Mage::getModel('imagetest/image')->load($id);
        if ($image->getId() && ($state !== null)){
            $image->setState($state);
            try{
                $image->save();
                return true;
            } catch(Exception $e) {
                return false;
            }
        }
        return false;
    }
    /**
     * Update Title and Comment at Image Servise
     * @param string $apiCode Code of Api Model
     * @param string $imageId Id of image at service
     * @param string $title Title on image service
     * @param string $comment Comment on image service
     * @return string
     */
    protected function _updateDataOnYoutube($apiCode, $imageId, $title, $comment)
    {
        $apiModel = Mage::getSingleton('imagetest/connector')->getApiModel($apiCode);
        if ($apiModel){
            $ret = $apiModel->updateImage($imageId, new Varien_Object(array('title'=>$title, 'description'=>$comment)));
            if ($ret->getSuccess()){
                return true;
            }
        }
        return false;
    }

    /**
     * Enable status of image
     * @param int|string $id
     * @return boolean
     */
    protected function _enableStatus($id)
    {
        return $this->_updateStatus($id, AW_Imagetest_Model_Image::IMAGE_STATUS_ENABLED);
    }

    /**
     * Disable status of image
     * @param int|string $id
     * @return boolean
     */
    protected function _disableStatus($id)
    {
        return $this->_updateStatus($id, AW_Imagetest_Model_Image::IMAGE_STATUS_DISABLED);
    }

    /**
     * Preview  of image
     * @param int|string $id
     * @return boolean
     */
    protected function _enablePreview($id)
    {
        return $this->_updateState($id, AW_Imagetest_Model_Image::IMAGE_STATE_PREVIEW);
    }

    /**
     * Dispreview  of image
     * @param int|string $id
     * @return boolean
     */
    protected function _disablePreview($id)
    {
        return $this->_updateState($id, AW_Imagetest_Model_Image::IMAGE_STATE_NOPREVIEW);
    }

    /**
     * Delete testimonial
     * @param int|string $id
     * @return boolean
     */
    protected function _delete($id)
    {
        $image = Mage::getModel('imagetest/image')->load($id);
        if ($image->getId()){
            try{
                $image->delete();
                return true;
            } catch(Exception $e) {
                return false;
            }
        }
        return false;
    }

    /**
     * Delete testimonial and source
     * @param int|string $id
     * @return boolean
     */
    protected function _fulldelete($id)
    {
        $image = Mage::getModel('imagetest/image')->load($id);
        if ($image->getId()){
            try{
                if (!$image->getReadOnly()){
                    $apiModel = Mage::getSingleton('imagetest/connector')->getApiModel($image->getApiCode());
                    if ($apiModel){
                        if ($image->getApiImageId()){
                            $delResult = $apiModel->deleteImage($image->getApiImageId());
                        }
                        if ($delResult->getError()){
                            $this->_addError($image->getApiCode() ? $image->getApiCode().': '.$delResult->getMessage() : $delResult->getMessage());
                            return false;
                        }
                    }
                }
                $image->delete();
                return true;
            } catch(Exception $e) {
                return false;
            }
        }
        return false;
    }

    /**
     * Add Success message for future show
     * @param string $message Message to show
     * @param mixed $value Value to show in string
     */
    protected function _addSuccess($message, $value = null)
    {
        $message = $value ? Mage::helper('imagetest')->__($message, $value) : Mage::helper('imagetest')->__($message);
        Mage::getSingleton('core/session')->addSuccess($message);
    }

    /**
     * Add Error message for future show
     * @param string $message Message to show
     * @param mixed $value Value to show in string
     */
    protected function _addError($message, $value = null)
    {
        $message = $value ? Mage::helper('imagetest')->__($message, $value) : Mage::helper('imagetest')->__($message);
        Mage::getSingleton('core/session')->addError($message);
    }

    /**
     * Edit form
     */
    public function editAction()
    {
        $id = $this->getRequest()->getParam('id');
        $ret = $this->getRequest()->getParam(AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_PENDING_KEY);
        $image = Mage::getModel('imagetest/image');
        if ($id){
            $image->load($id);
        }
        if ($image->getId() || $id == 0){
            $data = Mage::getSingleton('adminhtml/session')->getFormData(true);

            if (!empty($data)) {
                $image->setData($data);
            }

            # Set up default rate and votes
            if (!$image->getRate() && !$image->getVotes()){
                $image->setRate(0);
                $image->setVotes(0);
            }

            // Mage::register(AW_Imagetest_Model_Form_Element_Player::REGISTRY_KEY, $image->getApiCode() ? $image->getApiCode() : 'youtube');

            // if ($image->getState() == AW_Imagetest_Model_Image::IMAGE_STATE_PROCESSING){
            //    $image->getReady();
            // }

            Mage::register('image_data', $image);

            $this->loadLayout();
            $this->_setActiveMenu('catalog/imagetest');

            $this->_addBreadcrumb(Mage::helper('imagetest')->__('Image Testimonials'), Mage::helper('imagetest')->__('Image Testimonials'));
            $this->_addBreadcrumb(Mage::helper('imagetest')->__('Image edit'), Mage::helper('imagetest')->__('Image edit'));

            $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

            $form = $this->getLayout()->createBlock('imagetest/adminhtml_image_edit');
            if ($ret == AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_PENDING_ROUTE){
                $form->setIsPending(true);
            }
            $this->_addContent($form);
            $this->renderLayout();
        } else {
            $this->_addError('Testimonial not exists');
            $this->_redirect('*/*/'.(($ret == AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_PENDING_ROUTE)? 'pending' : ''));
        }
    }

    /**
     * Open seector of product for image review
     */
    public function newAction()
    {
        $id = $this->getRequest()->getParam('id');
        $ret = $this->getRequest()->getParam(AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_PENDING_KEY);



        $this->loadLayout();
        $this->_setActiveMenu('catalog/imagetest');

        $this->_addBreadcrumb(Mage::helper('imagetest')->__('Image Testimonials'), Mage::helper('imagetest')->__('Image Testimonials'));
        $this->_addBreadcrumb(Mage::helper('imagetest')->__('Image edit'), Mage::helper('imagetest')->__('Image edit'));

        $this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

        $form = $this->getLayout()->createBlock('imagetest/adminhtml_product_selector');
        if ($ret == AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_PENDING_ROUTE){
            $form->setIsPending(true);
        }
        $this->_addContent($form);
        $this->renderLayout();
    }


    public function addAction()
    {
        $this->_forward('edit');
    }


    protected function _getUpload()
    {
        return Mage::getSingleton('imagetest/upload');
    }

    /**
     * Retrives parsed image id from
     * [http://www.youtube.com/watch?v=<id>]
     * @param string $url
     * @return string
     */
    protected function _getParsedImageId($url)
    {
        if (html_entity_decode($url)){
            $arr = explode("?", $url);
            if (isset($arr[1])){
                $arr = explode("&", $arr[1]);
                $newArr = array();
                foreach($arr as $a){
                    try {
                        list($param, $value) = explode("=",$a);
                        $newArr[$param] = $value;
                    } catch(Exception $e) {
                        $this->_addError('Invalid image service url');
                        return null;
                    }
                }
                if (isset($newArr['v'])){
                    return $newArr['v'];
                } else {
                    $this->_addError('Invalid image service url');
                }
            }
        }
        return null;
    }


    /**
     * Product Selector grid for AJAX request
     */
    public function gridAction()
    {
        $this->loadLayout();
        $this->getResponse()->setBody(
            $this->getLayout()->createBlock('imagetest/adminhtml_product_selector_grid')->toHtml()
        );
    }

    /**
     * Save image
     */
    public function saveAction()
    {
        $id = $this->getRequest()->getParam('id');
        $back = $this->getRequest()->getParam('back');
        $pending = $this->getRequest()->getParam(AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_PENDING_KEY);

        $data = $this->getRequest()->getPost();

        $image = Mage::getModel('imagetest/image');

        # Save testimonial
        if ($id){
            try {
                $image->load($id);


                if ($image->getId()){
                	$data['created_at'] = date('Y-m-d H:i:s',strtotime($data['created_at']));
                    $image->addData($data);
                    try {
                        if ($_FILES['thumbnail']){
                            $uploader = new Mage_Core_Model_File_Uploader('thumbnail');
                            $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
                            $uploader->setAllowRenameFiles(true);
                            $uploader->setFilesDispersion(true);
                            $result = $uploader->save( Mage::getBaseDir('media') . DS . 'imagetestimonial'.DS );
                            $image->setThumbnail('imagetestimonial'.$result['file']);
                        }
                        $image->save();

                        $this->_addSuccess('Testimonial successfully saved');
                        if ($back){
                            $this->_redirectReferer();
                        } elseif($this->getRequest()->getParam(AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_FROM_KEY) == AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_FROM_PRODUCT) {
                            $params = array(
                                'id' => $this->getRequest()->getParam('product_id'),
                                'store' => $this->getRequest()->getParam('store'),
                                'tab' => 'product_info_tabs_imagetest',
                            );
                            $this->_redirect('adminhtml/catalog_product/edit', $params);
                        } else {
                            $this->_redirect('*/*/'.(($pending == AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_PENDING_ROUTE)? 'pending' : ''));
                        }
                    } catch (Exception $e) {
                        $this->_addError('Saving failed with error: %s', $e->getMessage());
                        $this->_redirectReferer();
                    }
                } else {
                    $this->_addError('Saving failed');
                    $this->_redirectReferer();
                }
            } catch (Exception $e) {
                $this->_addError('Saving failed with error: %s', $e->getMessage());
                $this->_redirectReferer();
            }

            # Upload image and create testimonial
        } else {
            $file = new Varien_Object(isset($_FILES['image_file']) ? $_FILES['image_file'] : array());
            $data = new Varien_Object($data);

            if ($error = $file->getError() && $data->getImageType() == 'file'){
                throw new Exception(Mage::helper('imagetest')->__($error));
                $this->_redirectReferer();
                return false;
            }

            $image = Mage::getModel('imagetest/image');

            # Set up basical info
            $image->setTitle($data->getTitle());
            $image->setComment($data->getComment());
            $image->setProductId($data->getProductId());
            $image->setAuthorName($data->getAuthorName());
            $image->setAuthorEmail($data->getAuthorEmail());
            $image->setRate($data->getRate());
            $image->setVotes($data->getVotes());
            //TODO Change this model
            //$image->setApiCode('youtube');
            $image->setState(AW_Imagetest_Model_Image::IMAGE_STATE_NOPREVIEW);

            if (Mage::app()->isSingleStoreMode()){
                # Get default store
                $defStore = 1;
                $stores = Mage::getModel('core/store')->getCollection();
                foreach($stores as $store){
                    if ($store->getId()){
                        $data->setStores(array($store->getId()));
                    }
                }
            }
            $image->setStores($data->getStores());

            $image->setStatus($data->getStatus());

            try {
                if ($data->getSourceType() == AW_Imagetest_Model_System_Config_Source_Image_Sourcetype::SOURCE_LINK){
                    // $entry = $this->_getApiModel($image->getApiCode())->getImageData($this->_getParsedImageId($data->getImageLink()));
                    //  if ($entry->getError()){
                    //   $entry = $this->_getApiModel($image->getApiCode())->getPublicImageData($this->_getParsedImageId($data->getImageLink()));
                    //  $image->setReadOnly(1);
                    //  }
                    // $image->setState(AW_Imagetest_Model_Image::IMAGE_STATE_READY);
                    $image->setApiImageUrl($data->getImageLink());
                } elseif($data->getSourceType() == AW_Imagetest_Model_System_Config_Source_Image_Sourcetype::SOURCE_FILE) {
                    // $entry = $this->_getApiModel($image->getApiCode())->uploadImage($file, $data);
                    //
                    $uploader = new Mage_Core_Model_File_Uploader('image_file');
                    $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
                    $uploader->setAllowRenameFiles(true);
                    $uploader->setFilesDispersion(true);
                    $result = $uploader->save( Mage::getBaseDir('media') . DS . 'imagetestimonial'.DS );
                    $image->setThumbnail('imagetestimonial'.$result['file']);

                } else {
                    $this->_addError('Post data corrupted');
                    $this->_redirectReferer();
                }

               /* if ($entry && $entry->getError()){
                    throw new Exception($entry->getMessage());
                }
                if (!$entry){
                    throw new Exception(Mage::helper('imagetest')->__('Answer of service not responsed. Try upload your image again.'));
                }

                if (!$entry->getImageUrl()){
                    //$this->_addError("You can't add this image. It's not for share");
                   // $this->_redirectReferer();
                   throw new Exception(Mage::helper('imagetest')->__("You can't add this image. It's not for share"));
                }

                $image->setApiImageId($entry->getId());
                if ($entry->getReady()){
                    $image->setApiImageUrl($entry->getImageUrl());
                    $image->setThumbnail($entry->getThumbnailUrl());
                    $image->setTime($entry->getTime());
               }*/

                //$date = new Zend_Date();
                $date = date('Y-m-d H:i:s',strtotime($data->getCreatedAt()));
                $image->setCreatedAt($date);

                $image->save();
                $this->_addSuccess('Your image successfully added');

                if ($back){
                    $this->_redirect('*/*/edit', array('id' => $image->getId()));
                } else {
                    $this->_redirect('*/*/');
                }
            } catch (Exception $e) {
                $this->_addError($e->getMessage());
                $this->_redirectReferer();
            }
        }
    }

    /**
     * Enable Testimonial
     */
    public function enableAction()
    {
        if ($id = $this->getRequest()->getParam('id')){
            if ($this->_enableStatus($id)){
                $this->_addSuccess('Status successfully updated');
            } else {
                $this->_addError('Status update failed');
            }
        }
        $this->_redirectReferer();
    }

    /**
     * Disable Testimonial
     */
    public function disableAction()
    {
        if ($id = $this->getRequest()->getParam('id')){
            if ($this->_disableStatus($id)){
                $this->_addSuccess('Status successfully updated');
            } else {
                $this->_addError('Status update failed');
            }
        }
        $this->_redirectReferer();
    }
   /**
     * preview Testimonial
     */
    public function previewAction()
    {
        if ($id = $this->getRequest()->getParam('id')){
            if ($this->_enablePreview($id)){
                $this->_addSuccess('preview successfully updated');
            } else {
                $this->_addError('preview update failed');
            }
        }
        $this->_redirectReferer();
    }

    /**
     * not preview Testimonial
     */
    public function dispreviewAction()
    {
        if ($id = $this->getRequest()->getParam('id')){
            if ($this->_disablePreview($id)){
                $this->_addSuccess('Do not preview successfully updated');
            } else {
                $this->_addError('Preview update failed');
            }
        }
        $this->_redirectReferer();
    }
    /**
     * Delete Testimonial
     */
    public function deleteAction()
    {
        $from = $this->getRequest()->getParam(AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_FROM_KEY);
        $pending =  $this->getRequest()->getParam(AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_PENDING_KEY);

        if ($id = $this->getRequest()->getParam('id')){
            if ($this->_delete($id)){
                $this->_addSuccess('Testimonial successfully deleted');
            } else {
                $this->_addError('Testimonial delete failed');
            }
        }
        if ($from == AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_FROM_EDIT){
            $this->_redirect('*/*/'.($pending ? 'pending' : ''));
        } elseif($this->getRequest()->getParam(AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_FROM_KEY) == AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_FROM_PRODUCT) {
            $params = array(
                'id' => $this->getRequest()->getParam('product_id'),
                'tab' => 'product_info_tabs_imagetest',
                'store' => $this->getRequest()->getParam('store'),
            );
            $this->_redirect('adminhtml/catalog_product/edit', $params);
        } else {
            $this->_redirectReferer();
        }
    }

    /**
     * Delete Testimonial and image form YouTube
     */
    public function fulldeleteAction()
    {
        $from = $this->getRequest()->getParam(AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_FROM_KEY);
        $pending =  $this->getRequest()->getParam(AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_PENDING_KEY);

        if ($id = $this->getRequest()->getParam('id')){
            if ($this->_fulldelete($id)){
                $this->_addSuccess('Testimonial and source successfully deleted');
            } else {
                $this->_addError('Testimonial and source delete failed');
            }
        }
        if ($from == AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_FROM_EDIT){
            $this->_redirect('*/*/'.($pending ? 'pending' : ''));
        } elseif($this->getRequest()->getParam(AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_FROM_KEY) == AW_Imagetest_Block_Adminhtml_Image_Grid::RETURN_FROM_PRODUCT) {
            $params = array(
                'id' => $this->getRequest()->getParam('product_id'),
                'tab' => 'product_info_tabs_imagetest',
                'store' => $this->getRequest()->getParam('store'),
            );
            $this->_redirect('adminhtml/catalog_product/edit', $params);
        } else {
            $this->_redirectReferer();
        }
    }

    /**
     * Mass update status
     */
    public function massUpdateStatusAction()
    {
        $images = $this->getRequest()->getParam('images');
        $status = $this->getRequest()->getParam('status');
        if ($images && is_array($images) && ($status !== null)){
            $success = $error = 0;
            foreach ($images as $id){
                if ($this->_updateStatus($id, $status)){
                    $success++;
                } else {
                    $error++;
                }
            }
            if ($success){
                $this->_addSuccess('%s testimonial(s) successfully updated', $success);
            }
            if ($error){
                $this->_addError('%s testimonial(s) update failed', $error);
            }
        } else {
            $this->_addError('Testimonial status update failed');
        }

        $this->_redirectReferer();
    }

    /**
     * Mass delete testimonials
     */
    public function massDeleteAction()
    {
        $images = $this->getRequest()->getParam('images');
        if ($images && is_array($images)){
            $success = $error = 0;
            foreach ($images as $id){
                if ($this->_delete($id)){
                    $success++;
                } else {
                    $error++;
                }
            }
            if ($success){
                $this->_addSuccess('%s testimonial(s) successfully deleted', $success);
            }
            if ($error){
                $this->_addError('%s testimonial(s) delete failed', $error);
            }
        } else {
            $this->_addError('Testimonial delete failed');
        }
        $this->_redirectReferer();
    }

    /**
     * Mass delete testimonials and image sources
     */
    public function massFulldeleteAction()
    {
        $images = $this->getRequest()->getParam('images');
        if ($images && is_array($images)){
            $success = $error = 0;
            foreach ($images as $id){
                if ($this->_fulldelete($id)){
                    $success++;
                } else {
                    $error++;
                }
            }
            if ($success){
                $this->_addSuccess('%s testimonial(s) and image source(s) successfully deleted', $success);
            }
            if ($error){
                $this->_addError('%s testimonial(s) and image source(s) delete failed', $error);
            }
        } else {
            $this->_addError('Testimonial(s) and image source(s) delete failed');
        }
        $this->_redirectReferer();
    }

    /**
     * Check admin permissions for this controller     *
     * @return boolean
     */
    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('catalog/imagetest');
    }
}
